import GlobalData from "../GlobalData";
import { ListenID } from "../ListenID";
import NetAdapter from "../adpapter/NetAdapter";
import { AlertManager, AlertType } from "../alert/AlertManager";
import { Common_UIPath } from "../common/Common_Define";
import { Notifier } from "../framework/Notifier";
import { Time } from "../framework/Time";
import { UIManager } from "../framework/UIManager";
import { Util } from "../utils/Util";
import DeviceManager from "./DeviceManager";
import DouyinManager from "./DouyinManager";
import { GameVoManager } from "./GameVoManager";
import KuaishouManager from "./KuaishouManager";

export default class AdManager {

    private static _instance: AdManager = null;
    public static get inst(): AdManager {
        return this._instance || (this._instance = new AdManager());
    }

    private isAndroid = cc.sys.isNative && cc.sys.os === cc.sys.OS_ANDROID;
    private isIOS = cc.sys.isNative && cc.sys.os === cc.sys.OS_IOS;

    private ecpm = '';

    private ToBid_RewardID = "6671746225899770";

    private price = '';
    iosLoadSplash() {
        if (this.isIOS) {
            jsb.reflection.callStaticMethod("AppController", "loadSplash");
        }
    }

    iosSplashCallback(res) {
        console.log("iosSplashCallback 跳转场景", res);
        cc.director.loadScene("GameLauncher");
    }

    laodAndroidAdReward() {
        console.log("laodAndroidAdReward======");
        if (!this.isAndroid) {
            return;
        }
        jsb.reflection.callStaticMethod("com/jingyingxiaobing/blueclient/AppActivity", "loadAdReward", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", GlobalData.inst.uid, this.ToBid_RewardID,  GlobalData.inst.token);
    }

    preLoadReward() {
        if (GlobalData.inst.tempHide) {
            return;
        }
        if (this.isIOS) {
            console.log("preLoadReward");
            jsb.reflection.callStaticMethod("AppController", "preLoadRewardVideoAd:", GlobalData.inst.uid.toString() || "userId123");
        }
    }

    private playRewardCallback: Function;
    private playRewardErrorCallback: Function;
    async playReward(callback: Function, errCallback?: Function) {
        if (GlobalData.inst.tempHide) {
            errCallback && errCallback("广告被临时隐藏");
            return;
        }
        console.log("playReward", cc.sys.isNative, cc.sys.os);

        const res = await NetAdapter.getUpdateHot()
        console.log("getUpdateHot res======", JSON.stringify(res))
        const info = res;
        GlobalData.inst.isTableScreen = info.is_table_screen
        if(info.is_kickback)
        {
            GlobalData.inst.is_kickback ='1';
        }else
        {
            GlobalData.inst.is_kickback ='0';
        }
        console.log("GlobalData.inst.is_kickback", GlobalData.inst.is_kickback);
        console.log("GlobalData.inst.isTableScreen", GlobalData.inst.isTableScreen);
        if (info.is_sim) {
            const hasSimCard = DeviceManager.inst.hasSimCard();
            console.log("hasSimCard======", hasSimCard)
            if (hasSimCard) {
            } else {
                AlertManager.showNormalTips("请插入SIM卡之后再试");
                errCallback && errCallback("SIM卡错误");
                return;
            }
        }


        Notifier.send(ListenID.TipsLoading_Show);

        this.playRewardCallback = callback;
        this.playRewardErrorCallback = errCallback;


        let adCallback = () => {
            //单机无广告测试，快手无广告直接过
            if (!GlobalData.inst.useNetWork || CC_DEV) {
                console.log("======ADa单机测试======");
                this.price = "0.02";
                this.playRewardCallback && this.playRewardCallback(this.price);
                this.hideLoading(1000);
                return;
            }

            //抖音小游戏取消广告次数调用
            if (Util.isDouyinGame()) {
                DouyinManager.inst.playReward((res) => {
                    this.hideLoading(1000);
                    if (res == "ok") {
                        this.playRewardCallback && this.playRewardCallback();
                    } else {
                        errCallback && errCallback();
                    }
                });
            } else if (Util.isKuaishouGame()) {
                KuaishouManager.inst.playReward((res) => {
                    this.hideLoading(1000);
                    if (res == "ok") {
                        this.playRewardCallback && this.playRewardCallback();
                    } else {
                        errCallback && errCallback();
                    }
                });
                // 快手小游戏取消广告次数调用
            } else if (this.isAndroid) {
                this.laodAndroidAdReward();
            } else if (this.isIOS) {
                jsb.reflection.callStaticMethod("AppController", "loadRewardVideoAd:", GlobalData.inst.uid.toString() || "userId123");
            }
        };
        NetAdapter.getUserInfo({ uid: GlobalData.inst.uid }).then(res => {
            console.log("adv_viewed_num:adv_viewed_all", res.adv_viewed_num, res.adv_viewed_all, res.equipmentid_adv_viewed_num);

            if (res.adv_viewed_num >= res.adv_viewed_all || res.equipmentid_adv_viewed_num >= res.adv_viewed_all) {
                AlertManager.showNormalTips("观看已达上限，明天再来");
                this.hideLoading(1000);
                errCallback && errCallback("广告次数超限");
                return;
            }
            else {
                adCallback();
            }
        }).catch(err => {
            this.hideLoading(1000);
            errCallback && errCallback("获取用户信息失败");
        })

    }

    loadJson() {
        cc.resources.load("testJson/list.json", (err, json) => {
            this.ecpm = json.ecpm;
        });
    }
    loadToBidRewaedOkCall(res) {
        console.log("loadToBidRewaedOkCall====================", res);

        let sendPlay = () => {
            if (this.isAndroid) {
                jsb.reflection.callStaticMethod("com/jingyingxiaobing/blueclient/AppActivity", "playAdReward", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", GlobalData.inst.uid, this.ToBid_RewardID, GlobalData.inst.token);
            } else if (this.isIOS) {
                // jsb.reflection.callStaticMethod("AppController", "showRewardVideoAd");
            }
        }

        if (res == "ok") {
            sendPlay();
        } else if (res == "close") {
            this.hideLoading(1000);
            this.playRewardErrorCallback && this.playRewardErrorCallback("广告被关闭");
        } else {
            this.hideLoading(1000);

            if (this.isIOS) {
                res = atob(res);
            }

            this.playRewardErrorCallback && this.playRewardErrorCallback("广告加载失败");
            let parse = JSON.parse(res);
            if (parse.type == "error" || parse.type == "not_ready") {
                AlertManager.showNormalTips(parse.msg);
            }
        }
    }
    public playToBidRewardCall(res) {
        console.log("playToBidRewardCall====================", res, res.search("ok"));
        if (res.includes("ok")) {
            if (this.isAndroid) {
                this.price = res.split("|")[1];
                let parse = JSON.parse(this.price);

                let data = parse.data;
                console.log("playToBidRewardCall====================");
                console.log(data);
                this.price = data.price;
                console.log("price", this.price);
            }
            this.hideLoading(1000);
            AlertManager.showNormalTips("奖励已发放");
            console.log("price", this.price);
            this.playRewardCallback && this.playRewardCallback(this.price + '');
        } else if (res.includes("close")) {
            console.log("close");
            this.playRewardErrorCallback && this.playRewardErrorCallback("广告被关闭");
            this.hideLoading(1000);
        }
        else {
            this.hideLoading(1000);

            if (this.isIOS) {
                res = atob(res);
            }

            this.playRewardErrorCallback && this.playRewardErrorCallback("广告加载失败");
            let parse = JSON.parse(res);
            if (parse.type == "error" || parse.type == "not_ready") {
                AlertManager.showNormalTips(parse.msg);
            }
        }
    }

    preLoadInterstitial() {
        if (GlobalData.inst.tempHide) {
            return;
        }
        if (this.isIOS) {
            console.log("preLoadInterstitial");
            jsb.reflection.callStaticMethod("AppController", "preLoadIntersititialAd:", GlobalData.inst.uid.toString() || "userId123");
        }
    }

    private currentAdWatcher: any = null; // 保存当前计时器的引用

    private clearCurrentWatcher() {
        if (this.currentAdWatcher) {
            Time.doCancal(this.currentAdWatcher); // 使用正确的清除方法
            this.currentAdWatcher = null;
        }
    }

    playInterstitialCallback: Function;
    playInterstitial(callback: Function, isChaping: boolean = false, errCallback?: Function) {
        if (GlobalData.inst.tempHide) {
            errCallback && errCallback("广告被临时隐藏");
            return;
        }
        console.log("playInterstitial");
        this.playInterstitialCallback = callback;
        if (Util.isDouyinGame()) {
            if (Time.gameTime > 30) {
                if (isChaping) {
                    console.log("等我62秒");
                    this.clearCurrentWatcher(); // 清除之前的计时器
                    this.currentAdWatcher = Time.delay(62, () => {
                        DouyinManager.inst.playCreateInterstitialAd();
                    }, null, null, -1)
                } else {
                    DouyinManager.inst.playCreateInterstitialAd();
                }
            }
            else {
                console.log(Time.gameTime)
            }
        } else if (Util.isKuaishouGame()) {
            if (Time.gameTime > 30) {
                if (isChaping) {
                    console.log("快手等我62秒");
                    this.clearCurrentWatcher(); // 清除之前的计时器
                    this.currentAdWatcher = Time.delay(62, () => {
                        KuaishouManager.inst.playCreateInterstitialAd();
                    }, null, null, -1)
                } else {
                    KuaishouManager.inst.playCreateInterstitialAd();
                }
            }
            else {
                console.log(Time.gameTime)
            }
        } else if (this.isAndroid) {
            jsb.reflection.callStaticMethod("com/jingyingxiaobing/blueclient/AppActivity", "playInterstitial", "()V");
        } else if (this.isIOS) {
            jsb.reflection.callStaticMethod("AppController", "loadIntersititialAd:", GlobalData.inst.uid.toString() || "userId123");
        }
    }

    playInterstitialCall(res) {
        if (res == "ok") {
            this.playInterstitialCallback && this.playInterstitialCallback(res);
        } else if (res == "close") {
            this.hideLoading(1000);
        } else {
            if (this.isIOS) {
                res = atob(res);
            }
            let parse = JSON.parse(res);
            if (parse.type == "error" || parse.type == "not_ready") {
                AlertManager.showNormalTips(parse.msg);
            } else if (parse.type == "ok") {
                this.playInterstitialCallback && this.playInterstitialCallback(parse);
            }
        }
    }

    showNativeAd(money: string) {
        if (Util.isDouyinGame() || Util.isKuaishouGame()) {
            // DouyinManager.inst.playCreateInterstitialAd();
        } else {
            if (this.isAndroid) {
                jsb.reflection.callStaticMethod("com/jingyingxiaobing/blueclient/AppActivity", "showNativeAd", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", GlobalData.inst.uid || "userId123", money, GlobalData.inst.is_kickback);
            } else if (this.isIOS) {
                jsb.reflection.callStaticMethod("AppController", "showNativeAd:money:is_kickback:", GlobalData.inst.uid.toString() || "userId123", money, GlobalData.inst.is_kickback);
            }
        }
    }

    hideLoading(time = 1) {
        setTimeout(() => {
            Notifier.send(ListenID.TipsLoading_Hide);
        }, time);
    }

    rewardCoin() {
        setTimeout(() => {
            NetAdapter.getRechargeDiamond().then(res => {
                Util.logExt(res, "获取看广告金币")
                try {
                    let info = res.info;
                    let rechargediamond = info.rechargediamond;
                    rechargediamond = parseInt(rechargediamond);
                    GameVoManager.getInstance.setDiamond(rechargediamond)
                    // Utils.createUI("prefab/AddCoinAlert").then((node: cc.Node) => {
                    //     node.getComponent(AddCoinAlert).setCoin(rechargediamond);
                    // })
                    NetAdapter.setRechargeDiamond({ rechargediamond: rechargediamond }).then(res => {
                        Util.logExt(res, "领取完广告金币");
                    })
                } catch (error) {
                    Util.logExt(error, "获取看广告金币数据解析错误");
                }
            })
        }, 1000);
    }

    alert(desc: string, log: any) {
        Util.logExt(log, desc);
        AlertManager.showAlert(AlertType.COMMON, {
            desc: desc,
            confirmText: "确认",
            cancelText: "取消",
            confirm: () => {
            },
            cancel: () => {
            }
        })
    }

    public sendHttp(res) {
        if (this.isIOS) {
            res = atob(res);
        }
        console.log("sendHttp res", res);
        let parse = JSON.parse(res);
        this.ecpm = parse.ecpm;
        //@ts-ignore
        let key = CryptoJS.MD5(parse.ecpm + "elite@thinkcmf").toString();
        //@ts-ignore
        let key2 = CryptoJS.MD5(key).toString();
        const randomString = AdManager.generateRandomString();
        NetAdapter.advOrderDev({
            uid: GlobalData.inst.uid,
            trans_id: parse.loadId,
            ecpm: parse.ecpm,
            ck_ecpm: key2,
        }).then(res => {
            this.price = res.price;
            Util.logExt(res, "advOrderDev:");
        }).catch(err => {
            Util.logExt(err, "advOrderDev err");
        });
    }

    private static generateRandomString() {
        let result = '';
        let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        let charactersLength = characters.length;

        for (var i = 0; i < 16; i++) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }

        return result;
    }
}

cc["AdManader"] = AdManager;
window["AdManader"] = AdManager;